package com.pllandxzx.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pll.dto.ResponseDto;
import com.pll.pojo.Admin;
import com.pll.util.ImageCodeUtils;
import com.pllandxzx.bean.MenuBean;
import com.pllandxzx.dto.ResponseDTO;
import com.pllandxzx.mapper.AdminMapper;
import com.pllandxzx.mapper.MenuMapper;
import com.pllandxzx.service.AdminService;
import com.pllandxzx.service.MenuService;
import com.pllandxzx.tool.BuildMenuTree;
import com.pllandxzx.vo.AdminVo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * @ClassName AdminServiceImpl
 * @Description TODO
 * @Author 阿⭐
 * @Date 2025/6/9 09:41
 */
@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AuthService authService;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private MenuMapper  menuMapper;

    @Autowired
    private BuildMenuTree buildMenuTree;

    @Override
    /**
     * @Description: 管理员登录
     * @Param: [adminVo, request]
     * @Return: com.pll.dto.ResponseDTO
     * @Author: 阿⭐
     * @Date: 2025/6/9
     */
    public ResponseDTO login(AdminVo adminVo, HttpServletRequest request) {
        if(!adminVo.getCode().equalsIgnoreCase(request.getSession().getAttribute("code").toString()) || adminVo.getCode() == null){
            return ResponseDTO.Fail(401,"验证码错误");
        }
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", adminVo.getAccount());
        queryWrapper.eq("password", adminVo.getPassword());
        //获取数据库中的管理员信息
        Admin admin = adminMapper.selectOne(queryWrapper);
        if (admin != null){//若管理员信息不为空
            HashMap<String, Object> data = authService.getToken(admin);
//            //获取管理员角色id
//            long roleId = admin.getRoleId();
//            //根据权限获取对应的菜单,构建菜单树
//            List<MenuBean> menuBeans = buildMenuTree.buildMenuTree(menuMapper.getMenuByRoleId(roleId));
//            //添加菜单树
//            data.put("menu",menuBeans);
            //返回管理员信息
            return ResponseDTO.Success(data);
        }
        return ResponseDTO.Fail(400, "账号或密码错误");
    }


    /**
     * @Description: 验证码生成
     * @Param: [response,session]
     * @Return:
     * @Author: 阿⭐
     * @Date: 2025/6/9
     */
    @Override
    public void capture(HttpServletResponse response, HttpSession session) {
        ImageCodeUtils imageCodeUtils = new ImageCodeUtils();
        String code = imageCodeUtils.getCode();
        try{
            imageCodeUtils.write(response.getOutputStream());
            session.setAttribute("code",code);
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
